<template>
  <div>
    <!-- 添加新行表单（以弹出框显示） -->
    <el-button type="primary" @click="showAddForm = true">添加</el-button>

    <el-dialog title="添加新行" v-model="showAddForm" width="50%" :before-close="handleCancel">
      <el-form ref="addForm" :model="formModel" label-position="left" label-width="80px" class="demo-ruleForm">
        <el-row>
          <!-- <el-col v-for="(column, index) in columns" :key="index" :sm="{ span: 24 / columns.length }"> -->
          <el-form-item v-for="(column, index) in columns" :key="index" :label="column.label">
            <el-input v-model="formModel[column.prop]" :placeholder="column.prop"></el-input>
          </el-form-item>
          <!-- </el-col> -->
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleAddSubmit">保存</el-button>
      </div>
    </el-dialog>
    <!-- 添加成功提示 -->
    <!-- <el-message v-if="showSuccessMessage" type="success" :duration="10000" message="添加成功!"></el-message> -->
    <el-select v-model="value2" multiple collapse-tags placeholder="Select" style="width: 240px"
      @change="handleColumnsChange">
      <el-option v-for="item in columns" :key="item.value" :label="item.label" :value="item.prop" />
    </el-select>
    <!-- table主体 -->
    <!-- <div class="draggable-table"> -->
    <!-- //原始表格 -->

    <el-table :data="tableData" fit style="width: 100%"    stripe border @header-dragend="handleDragEnd"
      highlight-current-row>
      <el-table-column label="操作" width="150px" resizable>
        <template #default="{ row }">
          <el-button size="small" @click="editRow(row)">编辑</el-button>
          <el-button size="small" @click="saveRow(row.id)" :disabled="!isEditing(row.id)">保存</el-button>
          <el-button size="small" @click="cancelEdit(row.id)" :disabled="!isEditing(row.id)">取消</el-button>
        </template>
      </el-table-column>
      <template v-for="(column, index) in columns" :key="index" index>
        <el-table-column :label="column.label" :width="column.width" min-width="0" resizable v-if="column.width !== 0">
          <template #default="{ row }">
            <el-form :model="row" label-width="0" style="max-width: 600px" label-position="left" v-if="row.isEditing">
              <el-form-item style="margin-bottom: 0px;">
                <el-select v-model="row[column.prop]" v-if="column.type == 'select'">
                  <el-option v-for="item in column.options" :key="item.id" :label="item.option" :value="item.option" />
                </el-select>
                <el-input input-style="color:red" class="align-center" v-model="row[column.prop]"  v-else></el-input>
              </el-form-item>
            </el-form>
            <span v-else class="align-center">{{ row[column.prop] }}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <!-- @header-dragend="handleHeaderDragEnd" -->
    <!-- 修改后可修改数据 -->


    <!-- </div> -->
    <!-- 分面组件 -->
    <el-pagination @update:current-page="handlePageChange" :current-page="currentPage" :page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]" :total="totalRows" layout="prev, pager, next, jumper, ->, total"
      style="margin-bottom: 10px; text-align: right;" @update:page-size="handlePageSizeChange" />
  </div>
</template>
  
<script setup>
import { ref, onMounted, computed, watch } from 'vue';
// import Sortable from 'sortablejs';
// import '../baseInfo/baseInfo.css';
import axios from "../../../utils/request";
// import { mainStore } from "../store";
import { transColumn } from '../../../api/tableApi';
import { useRoute } from 'vue-router';
// import { ElMessage } from 'element-plus'

const route = useRoute();
const value2 = ref([])
const currentPage = ref(1);
const pageSize = ref(10);
let totalRows;
let row = ref([]);
const tableData = ref([]);
const columns = ref([]);

// const formModel = ref({}); // 表单数据模型
const showAddForm = ref(false);
const showSuccessMessage = ref(false);
let url
let addUrl
let rawColumns = []
const editingRowId = ref(null);
let editingRowIndex = ref(null);

// const isEditing = (uid) => editingRowIndex === uid;


function handleHeaderDragEnd() {
  // 处理列宽改变的逻辑
}
// const currentMeta = ref(route.meta);
onMounted(async () => {

  console.log("OnMounted")
  console.log("route.meta", route.meta)
  url = route.meta.getpath;
  addUrl = route.meta.addpath
  console.log("addUrl", addUrl)

  // initTableHeaderDrag();
  try {
    const response = await getData(url, 1, 10);
    console.log(response);
    totalRows = response.data.count;
    var resdata = response.data.data
    var fieldData = response.data.fields
    console.log("fieldData", fieldData)
    console.log("resdata", resdata)
    setTableData(resdata, fieldData)
     } catch (error) {
    console.error('Failed to fetch data:', error);
  }
});
function handleDragEnd(newWidth, oldwidth,column) {
  console.log("handleDragEnd")
  console.log(columns.value)
  console.log(newWidth,oldwidth, column)
  let index = columns.value.findIndex(item => item.label === column.label)
  console.log('index',index)
  // if(index==-1){
  //   return
  // }
  // let newColumn = columns.value[index]
  let newColumn = columns.value.filter(item => item.label === column.label)[0];

  console.log(newColumn)//列中文名
}
watch(
  () => route.meta,
  async (newMeta, oldMeta) => {
    console.log("watch")

    if (JSON.stringify(newMeta) !== JSON.stringify(oldMeta)) {
      // console.log('Meta information has changed:', newMeta, 'Old:', oldMeta);
      currentPage.value = 1;
      console.log("route.meta", route.meta)
      url = newMeta.getpath;
      addUrl = route.meta.addpath
      console.log("addUrl", addUrl)
      var response = await getData(url, 1, 10);
      totalRows = response.data.count;
      var resdata = response.data.data
      var fieldData = response.data.fields

      //     ElMessage({
      //   message: '添加成功！！',
      //   type: 'success',
      //   duration: 2000

      // })
      setTableData(resdata, fieldData)
    }
  },
  { deep: true }
);
function isEditing(uid) {
  // console.log("isEditing", uid, editingRowIndex)
  return uid === editingRowIndex;
}
function getValue(row, prop){
  return row[prop]||''
}
function editRow(row) {
  console.log("editRow", row)
  tableData.value.forEach((row) => {
    row.isEditing = false;
  });


  editingRowIndex = row.id;
  // 更新表格数据的 isEditing 状态
  const editedRow = tableData.value.find((r) => r.id === row.id);
  console.log("editedRow", editedRow)
  console.log('editpath', route.meta.editpath)
  if (editedRow) {
    editedRow.isEditing = true;
  }
}

function saveRow(uid) {
  console.log("saveRow", uid)
  // console.log("formModel", formModel.value)
  // 保存更改到tableData
  const editedRow = tableData.value.find((row) => row.id === uid); // 假设 'id' 是行的唯一标识符
  console.log("editedRow", editedRow)
  if (editedRow) {
    delete editedRow.isEditing;
let res=axios.post(route.meta.editpath,editedRow)
console.log("res", res)
    // 使用 'uid' 更新对应的数据
    // editedRow = { ...editedRow, ...formModel.value };
    // formModel.value = {}; // 清空表单数据
    editedRow.isEditing = false;
    editingRowIndex = null; // 结束编辑
  }
}

function cancelEdit(uid) {
  console.log("cancelEdit", uid)
  // const editedRow = tableData.value.find((row) => row.id === uid); // 假设 'id' 是行的唯一标识符
  // if (editedRow && editingRowIndex === uid) {
  // 恢复原始数据
  // formModel.value = { ...editedRow };

  const editedRow = tableData.value.find((row) => row.id === uid);
  editedRow.isEditing = false;
  editingRowIndex = null; // 结束编辑
  // }
}

function setTableData(resdata, fieldData) {
  tableData.value = resdata;

  console.log("tableData", tableData.value)
  // 动态生成表格列
  // columns.value = transColumn(fieldData);
  columns.value = fieldData
  //  rawColumns=columns.value
  value2.value = []
  console.log("columns.value", columns.value)
  columns.value.forEach((item) => {
    rawColumns[item.prop] = item.width
    if(item.width!==0){
      value2.value.push(item.prop)
    }

  })
  //  console.log("columns.value",columns.value);
}
function getData(url, page, limit) {
  // let url = route.meta.getpath
  console.log(url)
  let newUrl = url + "?page=" + page + "&limit=" + limit
  return axios({
    url: newUrl,
    method: "get",
  })
}
function addData(data) {
  return axios({
    url: addUrl,
    method: "post",
    data: data
  })
}
// 选择数据项
function handleColumnsChange(values) {

  // 更新表格的列
  console.log('selectValues',values)
  columns.value.forEach(row => {
    if (values.includes(row.prop)) {
      row.width = rawColumns[row.prop]
    } else {

      row.width = 0;
    }
  })
  console.log("columns", columns.value)
}
// 分布组件API
const handlePageSizeChange = function (newPageSize) {

  console.log("newPageSize", newPageSize)
}
const handlePageChange = async (newPage) => {

  console.log("pageChangeUrl", newPage)
  currentPage.value = newPage;
  console.log("pageChangeUrl", url)
  const response = await getData(url, newPage, 10);
  tableData.value = response.data.data;
  console.log('handlePageChange', currentPage.value)
};

//处理添加请求
async function handleAddSubmit() {
  try {
    console.log(formModel.value);
    console.log("addUrl", addUrl)
    const response = await addData(formModel.value);
    console.log(response);
    if (response.data) {
      // tableData.value.push(response.data);
      formModel.value = {};
      showAddForm.value = false; // 关闭弹出框
      // showSuccessMessage.value = true;

      ElMessage({
        message: '添加成功！！',
        type: 'success',
        duration: 2000

      })

      // 可能需要额外操作，如刷新表格、显示成功提示等
    } else {
      console.error('添加失败:', response.statusText);
      // 处理添加失败的情况，如显示错误提示等
    }
  } catch (error) {
    console.error('添加过程中发生错误:', error);
    // 处理网络请求异常情况，如显示错误提示等
  }
}

// 取消添加操作，关闭弹出框
function handleCancel() {
  formModel.value = {};
  showAddForm.value = false;
}
</script>
<style scoped>
    .el-table {
      --el-border-color-lighter: #b7dcc0;
    }
    /* --el-table-border: 1px solid #b8e5c3; */
.el-form-item.align-center {
  display: flex;
  align-items: center;
  margin-bottom:0px 
}

:deep(.el-pagination .el-pagination__total.is-first.is-last) {
  color: #fff ;
}

:deep(.el-pagination__goto) {
  color: #fff ;
}
/* .align-center {
  text-align: center;
}

.el-form-item .el-select {
  height: inherit;
  line-height: inherit;
} */
</style>